package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.PermissionDao;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService{
    @Autowired
    private PermissionDao permissionDao;

    @Override
    public List<Permission> findAll(Integer id) {
        return permissionDao.findAll(id);
    }

    @Override
    public Role findById(Integer id) {
        return permissionDao.findById(id);
    }

    @Override
    public Integer[] findPermissionIdsByRoleId(Integer id) {
        return permissionDao.findPermissionIdsByRoleId(id);
    }

    @Override
    public void edit(Role role, Integer[] permissionIds) {
        permissionDao.edit(role);
        permissionDao.deleteAssociationByRoleId(role.getId());
        this.setRoleAndPermission(role.getId(),permissionIds);
    }
    public void setRoleAndPermission(Integer roleId,Integer[] permissionIds){
        if(permissionIds!=null || permissionIds.length>0){
            Map<String,Integer> map = new HashMap<>();
            for (Integer permissionId : permissionIds) {
                map.put("roleId",roleId);
                map.put("permissionId",permissionId);
                permissionDao.setRoleAndPermission(map);
            }
        }
    }
}
